package com.matrix.framework.web;

import org.reactivestreams.Publisher;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * MIME类型Web过滤器
 * 用于修正静态资源的Content-Type响应头，特别是.mjs文件
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025/9/20 11:00
 * @Since 1.2
 */
@Component
@Order(-1)
public class MimeTypeWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String path = exchange.getRequest().getPath().value();
        
        // 对于.mjs文件，使用自定义的响应装饰器
        if (path.endsWith(".mjs")) {
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(exchange.getResponse()) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    // 在写入响应体之前设置正确的Content-Type
                    if (getHeaders().containsKey("Content-Type")) {
                        getHeaders().remove("Content-Type");
                    }
                    getHeaders().set("Content-Type", "application/javascript; charset=utf-8");
                    return super.writeWith(body);
                }
            };
            
            return chain.filter(exchange.mutate().response(decoratedResponse).build());
        }
        
        return chain.filter(exchange);
    }
}